﻿using QRCoder;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        bool CompressFlag = true;
        const string text_compress = "待压缩文件路径:";
        const string text_decompress = "待解压文件路径:";

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            Control c = sender as Control;
            if(c.Name=="radioButton1")//压缩
            {
                CompressFlag = true;
                label1.Text = text_compress;
                btnExec.Text = "压缩";
                textBox1.Clear();
                textBox2.Clear();
            }
            else //解压缩
            {
                CompressFlag = false;
                label1.Text = text_decompress;
                btnExec.Text = "解压";
                textBox1.Clear();
                textBox2.Clear();
            }
        }

        private void btnFile1_Click(object sender, EventArgs e)
        {
            string text = CompressFlag ? "压缩" : "解压";
            openFileDialog1.Title = "选择待"+text+"文件";
            DialogResult rs=openFileDialog1.ShowDialog();
            if(rs==DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
            }
        }

        private void btnExec_Click(object sender, EventArgs e)
        {
            bool IsSuccess = false;
            try
            {
                if (CompressFlag)//压缩
                {
                    IsSuccess = CondenseRarOrZip(textBox1.Text, textBox2.Text);
                }
                else//解压缩
                {
                    IsSuccess = UnRarOrZip(textBox1.Text, textBox2.Text);
                }
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
           
            if (IsSuccess)
            {
                MessageBox.Show("操作成功");
            }
            else
            {
                MessageBox.Show("操作失败");
            }
        }
       

        private bool UnRarOrZip(string rarPathName, string UnPath)
        {
            if (!Directory.Exists(UnPath))
                Directory.CreateDirectory(UnPath);
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "Winrar.exe";
            startInfo.CreateNoWindow = true;
            //如果rarPathName 包含空格会导致查找不到指定路径下的解压文件
            string path = "\"" + rarPathName + "\"";
            string path2 = "\"" + UnPath + "\"";
            //覆盖命令( x -o+ 代表覆盖已存在的文件) 
            //-ibck 不显示解压窗口过程
            // -ilog 错误日志记录在winrar.exe文件路径下的err.log
            string cmd = string.Format(" x -o+ -ibck -ilog {0} {1} -y", path,path2); 
            startInfo.Arguments = cmd;
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
            //ExitCode==0正常执行；ExitCode==1 不正常
            if (process.ExitCode == 0)
            {
                process.Close();
                Console.WriteLine("解压成功");
                MessageBox.Show("解压成功");
                return true;
            }
            else
            {
                process.Close();
                Console.WriteLine("解压失败");
                MessageBox.Show("解压失败");
                return false;
            }

        }

        /// <summary>
        /// 压缩文件成RAR或ZIP文件(需存在Winrar.exe(只要自己电脑上可以解压或压缩文件就存在Winrar.exe))
        /// </summary>
        /// <param name="filePath">将要压缩的文件夹或文件绝对路径</param>
        /// <param name="rarPathName">压缩后的压缩文件保存绝对路径（包括文件名称）</param>
        private bool CondenseRarOrZip(string filePath, string rarPathName)
        {
            string rarPath = Path.GetDirectoryName(rarPathName);
            if (!Directory.Exists(rarPath))
                Directory.CreateDirectory(rarPath);
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "Winrar.exe";
            startInfo.CreateNoWindow = true;
            string cmd = string.Format(" a -ep1 -o+ {0} {1} -r", rarPathName, filePath); //压缩且覆盖已存在的文件
            startInfo.Arguments = cmd;
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
            //ExitCode==0正常执行；ExitCode==1 不正常
            if (process.ExitCode == 0)
            {
                process.Close();
                return true;
            }
            else
            {
                process.Close();
                return false;
            }
        }

        private void btnFile2_Click(object sender, EventArgs e)
        {
            DialogResult rs = folderBrowserDialog1.ShowDialog();
            if (rs == DialogResult.OK)
            {
                string filePath = folderBrowserDialog1.SelectedPath;
                string fileName=Path.GetFileNameWithoutExtension(textBox1.Text);
                textBox2.Text = filePath+"\\"+fileName;
                if(CompressFlag)
                {
                    textBox2.Text += ".rar";
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string file = textBox2.Text + "\\" + "OFD.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(file);
            XmlNamespaceManager npm = new XmlNamespaceManager(doc.NameTable);
            //npm.AddNamespace("ofd", doc.NamespaceURI); //doc.NamespaceURI
            //npm.AddNamespace("ofd", "http://www.ofdspec.org/2016");
            //XmlNode root = doc.DocumentElement;
            XmlNode root = doc.DocumentElement;
            npm.AddNamespace("ofd", root.NamespaceURI);
            XmlNode node = root.SelectSingleNode("ofd:DocBody/ofd:DocRoot", npm);
            if(node!=null)
            {
                string str = node.InnerXml;
            }

            ////创建BarcodeSettings对象
            //BarcodeSettings settings = new BarcodeSettings();

            ////设置条码类型为二维码
            //settings.Type = BarCodeType.QRCode;

            ////设置二维码数据
            //settings.Data = "01,10,011001900211,03108411,4,20200423,11762493383204597018,51B9,";

            ////设置显示文本
            //settings.Data2D = string.Empty;

            ////设置数据类型为数字
            //settings.QRCodeDataMode = QRCodeDataMode.Numeric;

            ////设置二维码错误修正级别
            //settings.QRCodeECL = QRCodeECL.H;

            ////设置宽度
            //settings.X = 2.0f;

            ////初始化BarCodeGenerator对象
            //BarCodeGenerator generator = new BarCodeGenerator(settings);

            ////创建图片并保存为PNG格式
            //Image image = generator.GenerateImage();
            //image.Save("QRCode.png");

            // 生成二维码的内容
            string strCode = "01,10,011001900211,03108411,4,20200423,11762493383204597018,51B9,";
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(strCode, QRCodeGenerator.ECCLevel.H);
            QRCode qrcode = new QRCode(qrCodeData);

            // qrcode.GetGraphic 方法可参考最下发“补充说明”
            Bitmap qrCodeImage = qrcode.GetGraphic(1, Color.Black, Color.White, null, 15, 6, false);
            pictureBox1.Image = qrCodeImage;
            //MemoryStream ms = new MemoryStream();
            //qrCodeImage.Save(ms, ImageFormat.Jpeg);

            // 如果想保存图片 可使用  qrCodeImage.Save(filePath);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 生成二维码的内容
            string strCode = "01,10,011001900211,03108411,4,20200423,11762493383204597018,51B9,";
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(strCode, QRCodeGenerator.ECCLevel.H);
            QRCode qrcode = new QRCode(qrCodeData);

            // qrcode.GetGraphic 方法可参考最下发“补充说明”
            Bitmap qrCodeImage = qrcode.GetGraphic(2, Color.Black, Color.White, null, 15, 6, false);
            pictureBox1.Image = qrCodeImage;
        }

        static Encoding encodeInstance = Encoding.GetEncoding("GB2312");
        private void button3_Click(object sender, EventArgs e)
        {
            string filename = string.Empty;
            string filecontent = string.Empty;
            string contentEncode = string.Empty;
            string contentDecode = string.Empty;
            string filename2 = string.Empty;
            byte[] bytes = new byte[0];
            byte[] bytes2 = new byte[0];
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Title = "选择压缩包文件";
                ofd.Filter = "|*.rar";
                DialogResult dr = ofd.ShowDialog();
                if(dr==DialogResult.OK)
                {
                    filename = ofd.FileName;
                }
            }
            if(!string.IsNullOrEmpty(filename))
            {
                using (FileStream fs = File.OpenRead(filename))
                {
                    bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                }
                contentEncode = encodeInstance.GetString(bytes);
                //contentEncode = EncodeBase64(encodeInstance, contentEncode);
                //contentEncode.Replace("+", "_");
                
                filename2 = filename.Substring(0, filename.LastIndexOf('.')) + "_2."+Path.GetExtension(filename);
                using (FileStream fs = new FileStream(filename2, FileMode.Create, FileAccess.Write))
                {
                    //contentDecode = contentEncode.Replace("_", "+");
                    //contentDecode = DecodeBase64(encodeInstance, contentDecode);
                    //bytes = encodeInstance.GetBytes(contentDecode);
                    //fs.Write(bytes, 0, bytes.Length);
                    bytes2 = encodeInstance.GetBytes(contentEncode);
                    fs.Write(bytes2,0,bytes2.Length);
                }
                string dir = filename2.Substring(0,filename2.LastIndexOf('.'));
                UnRarOrZip(filename2, dir);
            }
        }
        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="codeName">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public  string DecodeBase64(Encoding encode, string result)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }

        /// <summary>
        /// 将字符串转换为Base64字符串(encode编码格式)
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string EncodeBase64(Encoding encode, string code)
        {
            //string encode = "";
            byte[] bytes = encode.GetBytes(code);
            try
            {
                code = Convert.ToBase64String(bytes);
            }
            catch
            {
                code = code;
            }
            return code;
        }

        /* GetGraphic方法参数说明
                 public Bitmap GetGraphic(int pixelsPerModule, Color darkColor, Color lightColor, Bitmap icon = null, int iconSizePercent = 15, int iconBorderWidth = 6, bool drawQuietZones = true)
             * 
                 int pixelsPerModule:生成二维码图片的像素大小 ，我这里设置的是5 
             * 
                 Color darkColor：暗色   一般设置为Color.Black 黑色
             * 
                 Color lightColor:亮色   一般设置为Color.White  白色
             * 
                 Bitmap icon :二维码 水印图标 例如：Bitmap icon = new Bitmap(context.Server.MapPath("~/images/zs.png")); 默认为NULL ，加上这个二维码中间会显示一个图标
             * 
                 int iconSizePercent： 水印图标的大小比例 ，可根据自己的喜好设置 
             * 
                 int iconBorderWidth： 水印图标的边框
             * 
                 bool drawQuietZones:静止区，位于二维码某一边的空白边界,用来阻止读者获取与正在浏览的二维码无关的信息 即是否绘画二维码的空白边框区域 默认为true
   */
    }
}
